package com.doubao.notepad_blog_backend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doubao.notepad_blog_backend.common.api.ApiResult;
import com.doubao.notepad_blog_backend.domain.BmsPost;
import com.doubao.notepad_blog_backend.dto.CreatePostDTO;
import com.doubao.notepad_blog_backend.service.BmsPostService;
import com.doubao.notepad_blog_backend.utils.RedisUtil;
import com.doubao.notepad_blog_backend.vo.PostVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.util.List;
import java.util.Map;

import static com.doubao.notepad_blog_backend.jwt.JwtUtil.USER_NAME;

@RestController
@RequestMapping("/post")
@Api(value = "文章管理",tags = {"文章管理"})
public class BmsPostController {

    @Resource
    private BmsPostService postService;

    @Resource
    private RedisUtil redisUtil;

    @ApiOperation( "分页查文章" )
    @GetMapping("/list")
    public ApiResult<Page<PostVO>> list(@RequestParam(value = "tab", defaultValue = "latest") String tab,
                                        @RequestParam(value = "pageNo", defaultValue = "1")  Integer pageNo,
                                        @RequestParam(value = "size", defaultValue = "10") Integer pageSize) {
        Page<PostVO> list = postService.getList(pageNo,pageSize, tab);
        return ApiResult.success(list);
    }

    @ApiOperation( "创建文章" )
    @PostMapping("/create")
    public ApiResult<BmsPost> createPost(
            @RequestHeader(value = USER_NAME) String userName,
            @RequestBody CreatePostDTO createPostDTO) {
        BmsPost post = postService.createPost(userName, createPostDTO);
        return ApiResult.success(post);
    }


    @ApiOperation( "根据id获取文章详情" )
    @GetMapping
    public ApiResult getPostById(@RequestParam("id") String id) {
        Map<String, Object> map = postService.getPostById(id);
        return ApiResult.success(map);
    }

    @ApiOperation( "随便看看" )
    @GetMapping("/recommend")
    public ApiResult getRecommend(@RequestParam("postId") String id) {
        List<BmsPost> posts = (List<BmsPost>) redisUtil.get( "rand" );
        if(posts == null)
        {
            posts = postService.getRecommend(id);
            redisUtil.set("rand",posts,60*5);
        }

        return ApiResult.success(posts);
    }

    @ApiOperation( "修改文章" )
    @PostMapping("/update")
    public ApiResult<BmsPost> update(@RequestHeader(value = USER_NAME) String userName, @Valid @RequestBody BmsPost post) {
        post = postService.updateById(userName, post);
        return ApiResult.success(post);
    }

    @ApiOperation( "删除文章" )
    public ApiResult<String> delete(@RequestHeader(value = USER_NAME) String userName, @PathVariable("id") String id) {
        postService.deleteById(userName,id);
        return ApiResult.success(null, "删除成功");
    }


}

